package com.example.jedis.client.protocol.response;

import com.example.jedis.client.transport.RedisTransport;
import redis.clients.jedis.exceptions.JedisException;

import java.nio.ByteBuffer;
import java.util.List;

public class ResponseProtocolImpl implements ResponseProtocol {
    RedisTransport redisTransport;

    public RedisTransport getRedisTransport() {
        return redisTransport;
    }

    public void setRedisTransport(RedisTransport redisTransport) {
        this.redisTransport = redisTransport;
    }
    List<ApplyProtocol> applyProtocolList = null;

    public List<ApplyProtocol> getApplyProtocolList() {
        return applyProtocolList;
    }

    public void setApplyProtocolList(List<ApplyProtocol> applyProtocolList) {
        this.applyProtocolList = applyProtocolList;
    }

    private ApplyProtocol getApplyProtocol(byte flag){
       for(ApplyProtocol applyProtocol:applyProtocolList){
           if(applyProtocol.getFlag() ==flag){
               return applyProtocol;
           }
       }
       throw new JedisException("apply error flag:"+(char)flag);
    }
    @Override
    public Object read() {
        ByteBuffer byteBuffer = redisTransport.read();
        byteBuffer.flip();
        byte flag = byteBuffer.get();
        Object result = getApplyProtocol(flag).fromBytes(redisTransport,byteBuffer);
        return result;
    }
}
